// pages/orderSheet/myOrderSheet.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    active: '',
    imgPath: "/images",

    //订单范围
    orderScopes: ['全部订单', '待支付', '待收货', '已完成', '售后'],
    selectedScope: '全部订单',

    //订单数据
    orderList: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const util = require("../../utils/util")
    this.setData({
      imgPath: util.getImgPath()
    })

    //取出订单
    this.fetchOrder();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  onTabbarChange(event) {
    // console.log("onTabbarChange,event", event)
    this.setData({
      active: event.detail
    })
  },
  /**
   * 点击范围
   * @param {*} e 
   */
  tapScopeItem(e) {
    // console.log("tapScopeItem,e", e)
    let scopeName = e.currentTarget.dataset.scopeName;
    this.setData({
      selectedScope: scopeName
    })
    // let name=e.currentTarget

    //scopeName:'全部订单', '待支付', '待收货', '已完成', '售后'
    //show_status — 订单状态：0:未知，1：待支付， 2：已发货（待收货），3 已完成，4 申请售后
    let show_status = 0;
    switch (scopeName) {
      case '全部订单':
        show_status = 0;
        break;
      case '待支付':
        show_status = 1;
        break;
      case '待收货':
        show_status = 2;
        break;
      case '已完成':
        show_status = 3;
        break;
      case '售后':
        show_status = 4;
        break;
    }


    //取得订单数据
    this.fetchOrder(show_status);
  },
  /**
   * 取消订单
   * @param {*} e 
   */
  cancelOrder(e) {
    // console.log("cancelOrder", e)
    let orderNo = e.detail;

    wx.showModal({
      title: '取消订单',
      content: '确定取消该订单么？',
      complete: (res) => {
        //取消
        if (res.cancel) {

        }
        //确定
        if (res.confirm) {
          const api = require("../../api/api")
          api.user.orderDelete({
            order_sn: orderNo,
            success(res) {
              // console.log("取消订单，orderDelete,res", res);
              wx.showToast({
                title: '取消订单成功',
                icon: 'none'
              })

              wx.navigateTo({
                url: '/pages/orderSheet/myOrderSheet',
              })
            }
          })
        }
      }
    })
  },
  /**
   * 立即支付
   * @param {*} e 
   */
  payNow(e) {
    // console.log("payNow", e)
    let order_sn = e.detail;

    const api = require("../../api/api");
    api.order.payment({
      order_sn: order_sn,
      pay_type: 'wx',
      pay_client: "lite",
      success(resPayment) {
        // console.log("payment,resPayment", resPayment)

        if (resPayment.data.code != 0) {
          wx.showToast({
            title: resPayment.data.msg,
            icon: 'none'
          })
          return;
        }

        let dataPayment = resPayment.data.data;

        //如果data=="success"，不再发起支付
        if (dataPayment == "success") {
          wx.showToast({
            title: '订单已完成',
          })

          wx.navigateTo({
            url: '/pages/orderSheet/myOrderSheet',
          })

          return;
        }

        //微信支付
        wx.requestPayment({
          timeStamp: dataPayment.timeStamp,
          nonceStr: dataPayment.nonceStr,
          package: dataPayment.package,
          signType: 'MD5',
          paySign: dataPayment.paySign,
          success(resPay) {
            // console.log("wx.requestPayment,resPay", resPay)

            wx.navigateTo({
              url: '/pages/orderSheet/paySuccess',
            })
          },
          fail(resPay) {
            // console.log("wx.requestPayment,resPay", resPay)

            // wx.navigateTo({
            //   url: '/pages/orderSheet/payFail',
            // })
            wx.showToast({
              title: '支付失败',
              icon:'error'
            })

            //wx.navigateBack();
          }
        })
      }
    })

    // console.log("this.data.orderList",this.data.orderList);
    // let order=null;
    // for(let orderTemp of this.data.orderList){
    //   if(orderTemp.order_sn==order_sn){
    //     order=orderTemp;
    //   }
    // }
    // if(order==null){
    //   wx.showToast({
    //     title: '订单不存在',
    //     icon:'none'
    //   })
    //   return;
    // }
    // console.log("order",order)
    // return;

    // //设置订单数据
    // this.setOrderData(order_sn);

    // //订单支付
    // wx.navigateTo({
    //   url: '/pages/orderSheet/orderSetling',
    // })
  },
  //设置订单数据
  setOrderData(order_sn) {


    //规格
    if (this.data.specification == "") {
      wx.showToast({
        title: '请选择规格',
      })
      return;
    }
    let spec_stock_id = this.data.selectedTypeId + ',' + this.data.selectedSizeId;

    // 商品信息
    let goods_info = [{
      //名称
      name: this.data.name,
      //单价
      price: this.data.price,
      //图片
      goodsImages: this.data.goodsImages,
      //规格
      spec: this.data.specification,

      //商品标识
      goods_id: this.data.id,
      //购买数量
      buy_number: this.data.num,
      //规格
      spec_stock_id: spec_stock_id,
      //商品类型
      goods_type: this.data.goods_type,
      //运费
      transportation_fee: this.data.transportation_fee,
    }];

    //价格
    let price = Number(this.data.price) * Number(this.data.num);

    //收货信息
    let receive_info = {
      receive_mobile: '',
      receive_name: '',
      receive_address: ''
    };

    //优惠券标识
    let coupon_id = this.data.couponId;

    //保存订单信息到本地
    let order = {
      //商品信息
      goods_info,
      //总价格
      price,
      //收货信息
      receive_info,
      //优惠券标识
      coupon_id,
      //优惠券名称
      couponName: this.data.couponName,
      //优惠券价钱
      couponPrice: this.data.couponPrice,

    }
    // console.log("order", order)
    wx.setStorageSync('order', order);

    let orderReturn = wx.getStorageSync('order');
    // console.log('orderReturn', orderReturn);
  },
  /**
   * 申请售后
   * @param {*} e 
   */
  applyService(e) {
    // console.log("applyService", e)

    let order_sn = e.detail;
    wx.navigateTo({
      url: '/pages/orderSheet/applyAfterSale?order_sn=' + order_sn,
    })
  },
  /**
   * 确认收货
   * @param {*} e 
   */
  confirmReceipt(e) {
    // console.log("confirmReceipt", e)

    const that = this;

    //订单号
    let order_sn = e.detail;

    wx.showModal({
      title: '确认收货',
      content: '确认已收到货？',
      complete: (res) => {
        //取消
        if (res.cancel) {

        }
        //确定
        if (res.confirm) {
          const api = require("../../api/api")
          api.user.orderConfirm({
            order_sn: order_sn,
            success(res) {
              // console.log("orderConfirm,res", res)

              wx.navigateTo({
                url: '/pages/orderSheet/myOrderSheet',
              })
            }
          })
        }
      }
    })
  },
  buyAgain(e) {
    console.log("buyAgain", e)  //新增
    
    // this.triggerEvent("buyAgain", this.data.orderNo)
    // let goods =  this.data.detail.goods_info[0];
    // if (goods) {
    //   //跳转
    //   wx.navigateTo({
    //     url: '/pages/goods/detail?goods_id=' + goods.goods_id,
    //   })
    // } else {
    //   wx.showToast({
    //     title: '商品不存在',
    //   })
    // }
  },
  /**
   * 取得订单数据
   * @param {Number} show_status 订单状态：0:未知，1：待支付， 2：已发货（待收货），3 已完成，4 申请售后
   */
  fetchOrder(show_status) {
    let that = this;
    //show_status  订单状态：0:未知，1：待支付， 2：已发货（待收货），3 已完成，4 申请售后
    //'全部订单', '待支付', '待收货', '已完成', '售后'
    let status = "0";
    let logistics_status = "0";
    let is_apply_after_sale = "0";
    if (!show_status) show_status = 0;
    //let show_status=0;
    switch (this.data.selectedScope) {
      case '全部订单':
        // status="1,2";
        // logistics_status="1,2,3";
        // is_apply_after_sale="0,1";
        show_status = 0;
        break;
      case '待支付':
        //status = "1";
        //is_apply_after_sale = "0"
        show_status = 1;
        break;
      case '待收货':
        // status = "2";
        // logistics_status = "1,2";
        //is_apply_after_sale = "0"
        show_status = 2;
        break;
      case '已完成':
        // logistics_status = "3";
        //is_apply_after_sale = "0"
        show_status = 3;
        break;
      case '售后':
        // logistics_status="3";
        // is_apply_after_sale = "1"
        show_status = 4;
        break;
    }
    const api = require("../../api/api")
    api.user.orderList({
      page: 1,
      page_size: 1000,
      show_status: show_status,
      // status: status,
      // logistics_status: logistics_status,
      // is_apply_after_sale: is_apply_after_sale,
      success(res) {
        // console.log("orderList,res", res)
        if(res.data.code == 0){
        if(show_status == 0){
          let orderLIst = res.data.data.rows.filter(item => item.show_status != 4)
          res.data.data.rows = orderLIst
        }
       
        res.data.data.rows.forEach(function (element) {
          if(element.goods_info){
            element.goods_info.forEach(function (elm) {
              if(elm.goods_type == 300){
                elm.buy_number = elm.buy_number / 4 
              }
            })
          }
        });

        //将数据存入本地缓存
         wx.setStorageSync('orderList', res.data.data.rows);
        // console.log("本地缓存,orderList", wx.getStorageSync('orderList'));
         
        //将返回的数据放入data变量orderList
        that.setData({
          orderList: res.data.data.rows
        })
     }
      }

    })
  }
})